package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.crm.domain.pojo.Gate;
import com.yu.crm.domain.pojo.Region;
import com.yu.crm.domain.pojo.Station;
import com.yu.crm.mapper.RegionMapper;
import com.yu.crm.service.IRegionService;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.valid.ValidatorHelpers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zds
 * @since 2021-03-12
 */
@Service
public class RegionService extends ServiceImpl<RegionMapper, Region> implements IRegionService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    public void deleteByIds(String ids) {
        try {
            String substring = ids.substring(0, ids.length());
            String[] result = substring.split(",");
            List<Long> longList = new ArrayList<>();
            for (String s : result) {
                Region region = baseMapper.selectById(Long.valueOf(s));
                if (DataHelpers.isNotEmpty(region)) {
                    region.setIsDeleted(1);
                    ValidatorHelpers.validateDataSave(baseMapper.updateById(region));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    public Region infoById(Long id) {
        try {
            return baseMapper.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    public List<String> getRegionName(String stationName) {
        List<Region> regions = baseMapper.selectList(new QueryWrapper<Region>()
                .eq("station_name", stationName)
                .select("DISTINCT region_name")
                .eq("is_deleted", 0));
        return regions.stream().map(Region::getRegionName).collect(Collectors.toList());
    }

    public IPage getPage(Page<Region> page, String stationName, String condition) {
        QueryWrapper<Region> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        if (DataHelpers.isNotEmptyString(stationName)) {
            queryWrapper.eq("station_name", stationName);
        }
        if (DataHelpers.isNotEmptyString(condition)) {
            queryWrapper.and(i -> i.like("station_name", condition)
            );
        }
        return baseMapper.selectPage(page, queryWrapper);
    }
}
